import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Image } from 'react-native';

export interface Friend {
  _id: string;
  username: string;
  avatar: string;
  lastOnline: string;
  uid: string;
}

interface Props {
  friend: Friend;
  onPress?: (friend: Friend) => void;
}

export default function FriendItem({ friend, onPress }: Props) {
  const isOnline = () => {
    const lastOnline = new Date(friend.lastOnline);
    const now = new Date();
    // 如果最后在线时间在5分钟内，认为是在线的
    return now.getTime() - lastOnline.getTime() <= 5 * 60 * 1000;
  };

  return (
    <TouchableOpacity 
      style={styles.container}
      onPress={() => onPress?.(friend)}
    >
      <View style={styles.avatarContainer}>
        <Image 
          source={{ uri: friend.avatar }} 
          style={styles.avatar}
        />
        <View 
          style={[styles.onlineIndicator, 
            isOnline() ? styles.online : styles.offline
          ]}
        />
      </View>
      <View style={styles.info}>
        <Text style={styles.username}>{friend.username}</Text>
        <Text style={styles.uid}>ID: {friend.uid}</Text>
      </View>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 15,
    backgroundColor: 'white',
    marginHorizontal: 15,
    marginVertical: 8,
    borderRadius: 8,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.2,
    shadowRadius: 2,
  },
  avatarContainer: {
    position: 'relative',
  },
  avatar: {
    width: 50,
    height: 50,
    borderRadius: 25,
  },
  onlineIndicator: {
    position: 'absolute',
    right: 0,
    bottom: 0,
    width: 12,
    height: 12,
    borderRadius: 6,
    borderWidth: 2,
    borderColor: 'white',
  },
  online: {
    backgroundColor: '#4CAF50',
  },
  offline: {
    backgroundColor: '#9e9e9e',
  },
  info: {
    marginLeft: 15,
    flex: 1,
  },
  username: {
    fontSize: 16,
    color: '#333',
    fontWeight: 'bold',
  },
  uid: {
    fontSize: 12,
    color: '#666',
    marginTop: 4,
  },
});